package com.luocc.ccdemo.ui

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.luocc.ccdemo.R
import com.luocc.ccdemo.common.OnItemClickListener
import com.luocc.ccdemo.common.VideoListAdapter
import com.luocc.ccdemo.entity.Video
import com.luocc.ccdemo.vm.VideoViewModel

class VideoZoneFragment : Fragment() {
    private lateinit var mContext: Context
    private lateinit var mRefreshButton: ImageButton
    private lateinit var mRecyclerView: RecyclerView
    private lateinit var mAdapter: VideoListAdapter
    private lateinit var mVideoViewModel: VideoViewModel

    private val mItemClickListener = object : OnItemClickListener<Video> {
        override fun onClick(position: Int, obj: Video) {
            mVideoViewModel.insert(obj)
            val arg = Bundle(1)
            arg.putParcelable(VideoPlayingFragment.ARG_PARAM_VIDEO, obj)
            findNavController().navigate(R.id.action_videoZoneFragment_to_videoPlayingFragment, arg)
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mAdapter = VideoListAdapter(mContext)
        mAdapter.setOnItemClickListener(mItemClickListener)
        mVideoViewModel = ViewModelProvider(this).get(VideoViewModel::class.java)
        mVideoViewModel.getVideo(10)
        mVideoViewModel.getVideoList().observe(this) {
            Log.d(TAG, "onCreate submitList")
            mAdapter.submitList(it)
        }
        mVideoViewModel.getVideoEmpty().observe(this) {
            if (it) {
                Toast.makeText(mContext, "没有获取到数据", Toast.LENGTH_LONG).show()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val parent = inflater.inflate(R.layout.fragment_video_zone, container, false)
        mRecyclerView = parent.findViewById(R.id.video_list)
        mRefreshButton = parent.findViewById(R.id.refresh)
        val manager = LinearLayoutManager(mContext)
        mRecyclerView.layoutManager = manager
        mRecyclerView.adapter = mAdapter

        mRefreshButton.setOnClickListener {
            mVideoViewModel.getVideo(10)
        }
        return parent
    }

    companion object {
        private const val TAG = "LC_VideoZoneFragment"

    }
}